package jymsg;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 *
 * @author daniels
 */
public class YahooSessionListener implements Runnable {

    private Socket socket;
    private InputStream inSocket;
    private OutputStream outSocket;
    private String username;
    private boolean connected;
    private int session_id;
    private YahooSession caller;


    public YahooSessionListener(String username, Socket socket, InputStream inSocket, OutputStream outSocket, YahooSession caller) {

        this.username = username;
        this.socket = socket;
        this.inSocket = inSocket;
        this.outSocket = outSocket;
        this.connected = true;
        this.session_id = 0;
        this.caller = caller;
    }

    public void run() {
        
        while (!this.socket.isInputShutdown()) {

            YahooPacket pIn = new YahooPacket();
            try {
                pIn.readPacket(this.inSocket);
            } catch (IOException ex) {
                //do something
                pIn = null;
            } catch (BadYahooPacketException ex) {
                //do something
                pIn = null;
            }

            if (pIn != null) {
                this.session_id = pIn.getSessionId();
                switch (pIn.getService()) {
                    case YahooPacket.YAHOO_SERVICE_PING:
                        YahooPacket pOut = new YahooPacket();
                        pOut.setService(YahooPacket.YAHOO_SERVICE_PING);
                        pOut.setStatus(pIn.getStatus());
                        pOut.setSessionId(this.session_id);
                        try {
                            pOut.writePacket(this.outSocket);
                        } catch (IOException ex) {
                            //do something
                        }
                        break;

                    case YahooPacket.YAHOO_SERVICE_MESSAGE:
                        String from = pIn.getBody("4");
                        String to = pIn.getBody("5");
                        String message = pIn.getBody("14");
                        this.caller.OnMessage(from, to, message);
                        break;
                }
            }
        }
    }

    public int getSessionId() {

        return this.session_id;
    }
}
